package com.itfreer.map;

import android.app.Activity;
import android.app.Fragment;
import android.Manifest;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.itfreer.content.task.TaskActivity;
import com.itfreer.gis.ui.fragment.FragmentItem;
import com.itfreer.gis.ui.fragment.FragmentManager;
import com.itfreer.core.security.SecurityService;
import com.itfreer.core.security.UserInfoEntity;
import com.itfreer.gis.api.IMap;
import com.itfreer.gis.api.ISearch;
import com.itfreer.gis.config.GisConfigManager;
import com.itfreer.gis.locus.LocusEventData;
import com.itfreer.gis.offline.OfflineDataService;
import com.itfreer.gis.offline.OfflineSynService;
import com.itfreer.gis.styles.data.LayerInfo;
import com.itfreer.gis.ui.control.CentreControl;
import com.itfreer.gis.ui.control.DrawControl;
import com.itfreer.gis.ui.control.EditControl;
import com.itfreer.gis.ui.control.LocalControl;
import com.itfreer.gis.ui.control.LocusControl;
import com.itfreer.gis.ui.control.LocusInfoControl;
import com.itfreer.gis.ui.control.MenuControl;
import com.itfreer.gis.ui.control.NaviControl;
import com.itfreer.gis.ui.control.SearchControl;
import com.itfreer.gis.ui.control.ToolsControl;
import com.itfreer.gis.ui.fragment.LocusFragment;
import com.itfreer.gis.ui.fragment.SearchFragment;
import com.itfreer.map.commn.data.CLnOfflineData;
import com.itfreer.map.commn.data.CPtOfflineData;
import com.itfreer.map.commn.data.CPyOfflineData;
import com.itfreer.map.forestry.gd.data.GdSldcData2020;
import com.itfreer.map.forestry.hn.data.HnSldcData2020;
import com.itfreer.mapbox.ui.InfoControl;
import com.itfreer.metadata.version.AppVersion;
import com.itfreer.setting.configsyn.ConfigSynUtils;
import com.itfreer.setting.ui.SettingActivity;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.core.config.ConfigManager;
import com.itfreer.content.notice.MessageActivity;
import com.itfreer.core.collection.SerializableMap;
import com.itfreer.ui.advanced.SplashView;
import com.itfreer.utils.ClickUtils;
import com.itfreer.utils.ToastUtils;

import java.util.List;
import java.util.Map;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

/**
 * 主界面，全屏展示
 */
public class MainActivity extends BaseActivity implements ISearch.OnFindFeature, BaseActivity.OnFinish {

    // Fragment
    private Fragment fragment;
    // 查询框控件
    private SearchControl searchControl;
    // 地图工具
    private ToolsControl toolsControl;
    // 导航工具
    private NaviControl naviControl;
    // 定位工具
    private LocalControl localControl;
    // 绘制工具
    private DrawControl drawControl;
    // 中心点
    private CentreControl centreControl;
    // 编辑框
    private EditControl editControl;
    // 底部菜单工具
    private MenuControl menuControl;
    // 轨迹控件
    private LocusControl locusControl;
    // 轨迹展示控件
    private LocusInfoControl locusInfoControl;
    // 地图信息
    private InfoControl mapInfoControl;
    // 数据加载中
    private SplashView splashView;

    // 地图view
    private IMap mapView;

    private static final int REQUEST_CODE = 10;

    public MainActivity() {
        this.onFinish = this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 防止休眠
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setMenuBarColor();
        setNavigationBarColor();

        // 设置容器
        setContentView(R.layout.main_activity);

        // 地图初始化
        mapView = findViewById(R.id.mapView);
        // 查询框控件
        searchControl = findViewById(R.id.searchControl);
        // 地图工具
        toolsControl = findViewById(R.id.toolsControl);
        // 导航工具
        naviControl = findViewById(R.id.naviControl);
        // 定位工具
        localControl = findViewById(R.id.localControl);
        // 绘制工具
        drawControl = findViewById(R.id.drawControl);
        // 中心点
        centreControl = findViewById(R.id.centreControl);
        // 编辑框
        editControl = findViewById(R.id.editControl);
        // 底部菜单工具
        menuControl = findViewById(R.id.menuControl);
        // 轨迹控件
        locusControl = findViewById(R.id.locusControl);
        // 轨迹展示控件
        locusInfoControl = findViewById(R.id.locusInfoControl);
        // 地图信息
        mapInfoControl = findViewById(R.id.mapInfoControl);
        // 数据加载中
        splashView = findViewById(R.id.splashView);

        // 初始化配置
        mapView.onCreate(savedInstanceState);
        ConfigManager.setContext(this);
        ConfigManager.setLoading(splashView);
        GisConfigManager.setMap(mapView);
        mapView.init();

        // 初始化控件
        searchControl.setMeOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!ClickUtils.isFastClick()) return;

                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, SettingActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 1);
            }
        });
        searchControl.setMsgOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!ClickUtils.isFastClick()) return;

                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, MessageActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 2);
            }
        });
        // 地图工具
        toolsControl.setContainerViewId(R.id.fragment);
        searchControl.setContainerViewId(R.id.fragment);
        // 控件间关联关系
        menuControl.setEditControl(editControl);
        menuControl.setToolsControl(toolsControl);
        menuControl.setLeftText("资源分析");
        menuControl.setLeftMenuOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showShort(MainActivity.this, "功能开发中...");
            }
        });
        menuControl.setRightMenuOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!ClickUtils.isFastClick()) return;

                // 新建一个Intent对象
                Intent intent = new Intent();
                // 将map数据添加到封装的myMap中
                final SerializableMap dataMap = new SerializableMap();
                dataMap.setMap(null);
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", dataMap);
                intent.putExtras(bundle);
                // 指定intent要启动的类
                intent.setClass(MainActivity.this, TaskActivity.class);
                // 启动一个新的Activity
                startActivityForResult(intent, 4);
            }
        });
        menuControl.setCenterText(getString(R.string.menu_name));
//        menuControl.setCenterMenuOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                LocusUtils.create();
//            }
//        });
        editControl.setMenuControl(menuControl);
        editControl.setDrawControl(drawControl);
        editControl.setToolsControl(toolsControl);
        editControl.setCentreControl(centreControl);
        editControl.setSearchControl(searchControl);
        locusControl.setLocusInfoControl(locusInfoControl);
        mapInfoControl.init();

        // android6 执行运行时权限
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
            }
        }

        // 处理查询事项
        ISearch search = GisConfigManager.getSearch();
        search.setSearchOnFindFeature(this);

        // 强制版本更新
        AppVersion.instance.initVariable(this);
        AppVersion.instance.execute(false);

        // 处理用户登录，并更新配置
        SecurityService.instance.init(new SecurityService.UserListener() {
            @Override
            public void onSuccess(UserInfoEntity user) {
                ConfigSynUtils configSynUtils = new ConfigSynUtils(MainActivity.this);
                configSynUtils.configSyn(false, false);
            }

            @Override
            public void onGetJwt() {
                // 启动时数据同步一次
                OfflineSynService.instance.synData(false);
            }

            @Override
            public void onFail() {

            }
        });

        // 巡护事件
        FragmentManager.reg("gis_locus_event", LocusFragment.class);
        OfflineDataService.instance.regist("gis_locus_event", new LocusEventData());
        // 通用点线面
        OfflineDataService.instance.regist("fm_common_pt", new CPtOfflineData());
        OfflineDataService.instance.regist("fm_common_ln", new CLnOfflineData());
        OfflineDataService.instance.regist("fm_common_py", new CPyOfflineData());
        // 广洲资源
        OfflineDataService.instance.regist("gd_sldc_2019", new GdSldcData2020());
        // 湖南资源
        OfflineDataService.instance.regist("hn_sldc_2020", new HnSldcData2020());
    }

    /**
     * 查询回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String source = (String)bundle.get("source");
            Map<String, Object> where = (Map<String, Object>)bundle.get("datas");

            FragmentItem fragment = new SearchFragment();
            fragment.setData(where);
            fragment.setDataName(source);
            FragmentTransaction ft2 = ((Activity)ConfigManager.getContext()).getFragmentManager().beginTransaction();
            ft2.replace(R.id.fragment, (Fragment)fragment);
            ft2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            ft2.addToBackStack(null);
            ft2.commit();
        }
    }

    @Override
    public void onFind(LayerInfo layer, Object feature) {
        FragmentManager.startFragment(R.id.fragment, layer.getSourceInfo().getSource(), feature);
    }

    @Override
    public void onUnFind() {
        FragmentManager.popBackStack();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 按下键盘上返回按钮
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            List<Fragment> fragments = this.getFragmentManager().getFragments();
            if (fragments == null || fragments.size() <= 1) {
                return onKeyDown2(keyCode, event);
            } else {
                FragmentManager.popBackStack();
                return true;
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private boolean onKeyDown2(int keyCode, KeyEvent event) {
        if(canExit()){
            if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
                if((System.currentTimeMillis()-exitTime) > 2000){
                    Toast.makeText(getApplicationContext(), "再按一次，数据同步后将退出系统", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    if(onFinish!=null) onFinish.onFinish();
                    // 启动时数据同步一次
                    Toast.makeText(getApplicationContext(), "数据同步后将退出系统，请稍后...", Toast.LENGTH_SHORT).show();
                    ConfigManager.getLoading().setVisible(true);
                    // 处理用户登录，并更新配置
                    SecurityService.instance.init(new SecurityService.UserListener() {
                        @Override
                        public void onSuccess(UserInfoEntity user) {
                            if(user==null){
                                finish();
                                System.exit(0);
                            }
                        }

                        @Override
                        public void onGetJwt() {
                            OfflineSynService.instance.synData(false, new OfflineSynService.ProgressListener() {
                                @Override
                                public void onSize(int count, int size, String msg) {
                                }

                                @Override
                                public void onFail(String info) {
                                    finish();
                                    System.exit(0);
                                }

                                @Override
                                public void onSuccess() {
                                    finish();
                                    System.exit(0);
                                }
                            });
                        }

                        @Override
                        public void onFail() {
                            finish();
                            System.exit(0);
                        }
                    });
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    // 退出时，提交一次数据
    @Override
    public void onFinish() {
    }

    /**
     * 返回时，是否可以退出
     *
     * @return
     */
    @Override
    protected boolean canExit() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 获取权限结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted准许
            } else {
                // Permission Denied拒绝
            }
        }
    }
}